package com.yeskery.nut.util;

import com.yeskery.nut.core.NutException;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * IP工具类
 * @author sprout
 * 2022-05-13 11:16
 */
public class IPUtils {

    /**
     * 私有化构造方法
     */
    private IPUtils() {
    }

    /**
     * 获取所有本地ip
     * @return 所有本地ip
     */
    public static Map<String, List<String>> getAllLocalIp() {
        return getAllLocalIp(true);
    }

    /**
     * 获取所有本地ip
     * @param onlyIpV4 只获取ipv4地址
     * @return 所有本地ip
     */
    public static Map<String, List<String>> getAllLocalIp(boolean onlyIpV4) {
        Map<String, List<String>> map = new HashMap<>(16);
        Enumeration<NetworkInterface> e1;
        try {
            e1 = NetworkInterface.getNetworkInterfaces();
            while (e1.hasMoreElements()) {
                NetworkInterface ni = e1.nextElement();

                List<String> ips = new LinkedList<>();
                map.put(ni.getName(), ips);

                Enumeration<InetAddress> e2 = ni.getInetAddresses();
                while (e2.hasMoreElements()) {
                    InetAddress ia = e2.nextElement();
                    if(ia instanceof Inet6Address) {
                        if (onlyIpV4) {
                            continue;
                        }
                    }
                    ips.add(ia.getHostAddress());
                }
            }
        } catch (SocketException e) {
            throw new NutException("Failed To Get Local IP Address", e);
        }
        return map;
    }
}
